<?php

/**
 * Elgg oauth2 server
 * 
 * @author _Nam
 * @copyright Greengar studios
 * @link http://www.greengarstudios.com
 */
// Get config
global $CONFIG;

// include the OAuth2 library
include($CONFIG->pluginspath . 'greengar/oauth2/lib/OAuth2.inc');
include($CONFIG->pluginspath . 'greengar/oauth2/lib/OAuth2Client.inc');
include($CONFIG->pluginspath . 'greengar/oauth2/lib/OAuth2Exception.inc');

// set up the data store
include($CONFIG->pluginspath . 'greengar/oauth2/lib/ElggOAuth2DataStore.php');

function oauth2_init() {

    // run our set up and upgrade functions
    run_function_once('oauth2_run_once');
}

// register our token and consumer objects
function oauth2_run_once() {
    // Register a class
    add_subtype('object', 'greengar_oauth2_client');
    add_subtype('object', 'greengar_oauth2_token');
    add_subtype('object', 'greengar_oauth2_code');
}

$OAUTH_SERVER = NULL;

// get or create an OAuth server
function oauth2_get_server() {
    global $OAUTH_SERVER; // cache the object
    if (!$OAUTH_SERVER) {
        $OAUTH_SERVER = new ElggOAuth2DataStore();
    }
    return $OAUTH_SERVER;
}

function oauth2_auth_password($email, $password) {
    //$user = get_user_by_email($email);
    
    $_uid = get_user_id_by_email($email);
    
    // compatible with old client
    if(!$_uid) {
        $user = get_user_by_email($email);
        if($user && is_array($user)) {
            $user = array_shift($user);
        }
    }
    else {
        $user = get_user($_uid);
    }
    if ($user) {
           
        $check = FALSE;
        
        if (strlen($user->password) <= 32) {
            $check = ($password == md5($password));
        } else {
            $hasher = new PasswordHash(8, TRUE);
            $check = $hasher->CheckPassword($password, $user->password);
        }
        
        if ($user->password == generate_user_password($user, $password)) {
            $check = TRUE;
        }
        
        if ($check) {
            login($user);
            $client_id = get_input('client_id');
            $user->clearMetaData($client_id);
            $user->setMetadata($client_id, 1);
            $user->save();
            return TRUE;
        }
    }
    return FALSE;
}

function oauth2_page_guardian() {
    $oauth = oauth2_get_server();
    $oauth->verifyAccessToken();
}

register_elgg_event_handler('init', 'system', 'oauth2_init');
?>
